package com.taysear.parcel;

import java.util.Date;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;

import com.taysear.parcel.domain.User;
import com.taysear.parcel.util.Constants;
import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.addon.jpacontainer.JPAContainerFactory;
import com.vaadin.data.util.filter.And;
import com.vaadin.data.util.filter.Compare.Equal;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.LoginForm;
import com.vaadin.ui.LoginForm.LoginEvent;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window.Notification;

public class LoginScreen extends VerticalLayout {
	private static final long serialVersionUID = -3060144396783698031L;
	private ParcelApplication app;

	public LoginScreen(ParcelApplication app) {
		this.app = app;

		// The application caption is shown in the caption bar of the browser window.
		this.app.getMainWindow().setCaption("Parcels");

		setSizeFull();

		Panel loginPanel = new Panel("Login");
		loginPanel.setWidth("400px");

		LoginForm loginForm = new LoginForm();
		loginForm.setPasswordCaption("Password");
		loginForm.setUsernameCaption("User");
		loginForm.setLoginButtonCaption("Login");

		loginForm.setHeight("120px");
		loginForm.addListener(new MyLoginListener(this.app, loginForm));

		loginPanel.addComponent(loginForm);

		addComponent(loginPanel);
		setComponentAlignment(loginPanel, Alignment.MIDDLE_CENTER);

		HorizontalLayout footer = new HorizontalLayout();
		footer.setHeight("50px");
		addComponent(footer);
	}

	private static class MyLoginListener implements LoginForm.LoginListener {
		private static final long serialVersionUID = -9052382186242467136L;
		private ParcelApplication app;
		private LoginForm loginForm;

		public MyLoginListener(ParcelApplication app, LoginForm loginForm) {
			this.app = app;
			this.loginForm = loginForm;
		}

		@Override
		public void onLogin(LoginEvent event) {
			String username = event.getLoginParameter("username");
			String password = User.hash(event.getLoginParameter("password"));

			try {
				ParcelApplication.getInstance().login(username, password);
				And and = new And(new Equal("username",username), new Equal("password",password));
				JPAContainer<User> users = JPAContainerFactory.make(User.class, app.PERSISTENCE_UNIT);
				users.addContainerFilter(and);
				User user = users.getItem(users.firstItemId()).getEntity();
				Boolean employeeStatusInActive = user.getEmployee().getEmployeeStatus().getEmployeeStatusId() == Constants.EMPLOYEE_STATUS_IN_ACTIVE;
				
				Boolean employmentTerminated = user.getEmployee().getTerminatedDate() != null;
				if(employmentTerminated) {
					Date now = app.getDateWithoutTime(new Date());
					Date dateEndOfEmployment = user.getEmployee().getTerminatedDate();
					int dateCompare = dateEndOfEmployment.compareTo(now);
					employmentTerminated = dateCompare == -1;
				}
				
				Boolean stationStatusInActive = user.getEmployee().getStation().getStationStatus().getStationStatusId() == Constants.STATION_STATUS_IN_ACTIVE;
				Boolean substationStatusInActive = user.getEmployee().getSubstation().getStationStatus().getStationStatusId() == Constants.STATION_STATUS_IN_ACTIVE;
				if(employeeStatusInActive | employmentTerminated |stationStatusInActive | substationStatusInActive)
					throw new Exception("Employee, station or substation status is inactive");
				ParcelApplication.getInstance().setUser(user);
				// Switch to the protected view
				app.getMainWindow().setContent(new MainLayout(app));
			} catch (UnknownAccountException uae) {
				app.showNotification("Invalid User");
			} catch (IncorrectCredentialsException ice) {
				app.showNotification("Invalid User");
			} catch (LockedAccountException lae) {
				app.showNotification("Invalid User");
			} catch (ExcessiveAttemptsException eae) {
				app.showNotification("Invalid User");
			} catch (AuthenticationException ae) {
				app.showNotification("Invalid User");
			} catch (Exception ex) {
				app.showNotification("Exception " + ex.getMessage());
			}
		}
	}
}